package com.baidu.sggc.core.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@Service
public class MailService {

    @Autowired
    private JavaMailSender mailSender;

    // 1. 发送简单文本邮件
    public void sendSimpleMail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(mailSenderUsername()); // 发件人
        message.setTo(to);                     // 收件人
        message.setSubject(subject);           // 邮件主题
        message.setText(content);              // 邮件内容
        mailSender.send(message);
    }

    // 2. 发送HTML邮件
    public void sendHtmlMail(String to, String subject, String htmlContent) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
        helper.setFrom(mailSenderUsername());
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(htmlContent, true); // true = HTML
        mailSender.send(message);
    }

    // 3. 发送带附件的邮件
    public void sendAttachmentMail(String to, String subject, String content, File file) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
        helper.setFrom(mailSenderUsername());
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, false);
        // 添加附件
        FileSystemResource fileResource = new FileSystemResource(file);
        helper.addAttachment(file.getName(), fileResource);
        mailSender.send(message);
    }

    // 4. 可选：获取配置里的发件人
    @Autowired
    private org.springframework.core.env.Environment env;
    private String mailSenderUsername() {
        return env.getProperty("spring.mail.username");
    }
}
